//
//  HomeViewController.m
//  AppointmentForCar
//
//  Created by Herron on 16/10/2.
//  Copyright © 2016年 Herron. All rights reserved.
//

#import "HomeViewController.h"
#import "MyCenterViewController.h"
#import "GeoCodeSearchManager.h"
#import "SearchNearPointViewController.h"
#import "AddressSelectView.h"
#import "HomeViewModel.h"
#import "RideHailingViewController.h"

@interface HomeViewController ()<BMKMapViewDelegate,BMKLocationServiceDelegate , AddressSelectViewDelegate , SearchNearPointViewControllerDelegate , RideHailingViewControllerDelegate>

@property (weak, nonatomic) IBOutlet BMKMapView *mapView;
@property (nonatomic, strong) BMKLocationService *locService;
@property (nonatomic , strong) GeoCodeSearchManager *searchAddress;
@property (nonatomic , strong) HomeViewModel *model;
@property (nonatomic , weak) AddressSelectView *addressSelect;
@property (nonatomic , copy) NSString *cityName;

@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, assign) NSInteger repeatCount;

@end

@implementation HomeViewController {
    BMKPointAnnotation * _annotation;
    BMKAnnotationView * _annotationView;
    BMKPoiInfo * _destinationInfo;
    BMKPoiInfo * _originInfo;
    NSString * _currentAddress; // 起点
    NSString * _destinationAddress; // 终点
    BOOL _isUserLocation;
    BOOL _isDecoding;
}

- (void)viewDidLoad {
    
    [super viewDidLoad];

    _repeatCount = 0;
    
    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 36, 36)];
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 36, 36)];
    [imageView setImage:[UIImage imageNamed:@"m-icon"]];
    imageView.layer.cornerRadius = 18;
    imageView.layer.masksToBounds = YES;
    [titleView addSubview:imageView];
    self.navigationItem.titleView = titleView;

    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"myCenter"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(myCenter)];
    
    _locService = [[BMKLocationService alloc]init];
    [_mapView setShowsUserLocation:YES];
    _mapView.zoomLevel = 18;
}

- (void)selectDestination:(UIButton *)sender {
    SearchNearPointViewController * controller = [[SearchNearPointViewController alloc] init];
    [self.navigationController pushViewController:controller animated:YES];
}

-(void)viewWillAppear:(BOOL)animated {
    self.navigationController.navigationBar.translucent = NO;
    [self.mm_drawerController setOpenDrawerGestureModeMask:MMOpenDrawerGestureModeNone];
    self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];

    [_mapView viewWillAppear];
    _mapView.delegate = self;
    _locService.delegate = self;
    [_locService startUserLocationService];
    _mapView.showsUserLocation = NO;
    _mapView.userTrackingMode = BMKUserTrackingModeFollow;
    _mapView.showsUserLocation = YES;
    
//    self.addressSelect.isDestination = NO;
    self.addressSelect.destination = _destinationAddress;

}

-(void)viewWillDisappear:(BOOL)animated {
    [_mapView viewWillDisappear];
    [_locService stopUserLocationService];
    _mapView.delegate = nil; // 不用时，置nil
    _locService.delegate = nil;
    _addressSelect.destination = @"您要去哪儿";
}


#pragma mark - BMKMapViewDelegate
- (void)mapView:(BMKMapView *)mapView regionWillChangeAnimated:(BOOL)animated {
    _annotation.title = @"";
    _annotationView.paopaoView.hidden = YES;
    [_annotation setCoordinate:_mapView.centerCoordinate];
}

- (void)mapView:(BMKMapView *)mapView regionDidChangeAnimated:(BOOL)animated {
    if(!_isUserLocation) {
        return;
    }
//    self.addressSelect.origin = nil;
    [_annotation setCoordinate:_mapView.centerCoordinate];
    _isDecoding = YES;
    _annotation.title = @"";
    _annotationView.paopaoView.hidden = YES;
    [self.searchAddress reverseGeocodeSearchOptionWithLocationCoordinate2D:_mapView.centerCoordinate results:^(NSString *address , NSString * city) {
        _annotation.title = address;
        _cityName = city;
        _annotationView.paopaoView.hidden = NO;
        if ( 0 == self.addressSelect.origin.length) {
            self.addressSelect.origin = address;
            _currentAddress = address;
        }
        [_annotationView setSelected:YES animated:YES];
        _isDecoding = NO;
    }];
}


- (void)mapView:(BMKMapView *)mapView didAddAnnotationViews:(NSArray *)views {
    self.addressSelect.isDestination = NO;
//    self.addressSelect.origin = nil;
    [_annotation setCoordinate:_mapView.centerCoordinate];
    [self.searchAddress reverseGeocodeSearchOptionWithLocationCoordinate2D:_mapView.centerCoordinate results:^(NSString *address , NSString * cityName) {
        _annotation.title = address;
        _cityName = cityName;
        _annotationView.paopaoView.hidden = NO;
        if ( 0 == self.addressSelect.origin.length) {
            self.addressSelect.origin = address;
            _currentAddress = address;
        }
        [_annotationView setSelected:YES animated:YES];
    }];
}

- (void)mapView:(BMKMapView *)mapView onDrawMapFrame:(BMKMapStatus*)status {
    [_annotation setCoordinate:_mapView.centerCoordinate];
}

- (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id <BMKAnnotation>)annotation {
    // 生成重用标示identifier
    NSString *AnnotationViewID = @"xidanMark";
    
    // 检查是否有重用的缓存
    BMKAnnotationView* annotationView = [mapView dequeueReusableAnnotationViewWithIdentifier:AnnotationViewID];
    
    if (annotationView == nil) {
        annotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID];
        ((BMKPinAnnotationView*)annotationView).pinColor = BMKPinAnnotationColorRed;
        ((BMKPinAnnotationView*)annotationView).animatesDrop = YES;
    }
    
    annotationView.centerOffset = CGPointMake(0, -(annotationView.frame.size.height * 0.5));
    annotationView.annotation = annotation;
    annotationView.canShowCallout = YES;
    annotationView.draggable = YES;
    [annotationView setSelected:YES animated:YES];
    _annotationView = annotationView;
    
    return annotationView;
}

#pragma mark - BMKLocationServiceDelegate
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation {
    [_locService stopUserLocationService];
    CLLocationCoordinate2D pt = (CLLocationCoordinate2D){0, 0};
    pt = (CLLocationCoordinate2D){_locService.userLocation.location.coordinate.latitude,
        _locService.userLocation.location.coordinate.longitude};
    _mapView.showsUserLocation = NO;
    _mapView.userTrackingMode = BMKUserTrackingModeFollow;
    _mapView.showsUserLocation = YES;
    [_mapView setCenterCoordinate:pt];
    if(!_annotationView) {
        CLLocationCoordinate2D pt = (CLLocationCoordinate2D){0, 0};
        pt = (CLLocationCoordinate2D){_locService.userLocation.location.coordinate.latitude,
            _locService.userLocation.location.coordinate.longitude};
        _annotation = [[BMKPointAnnotation alloc] init];
        [_annotation setCoordinate:pt];
        [_mapView addAnnotation:_annotation];
    }
    _isUserLocation = YES;
}

#pragma mark - searchControllerDelegate
- (void)searchNearPointWithResult:(BMKPoiInfo *)result type:(NSString *)type{
    if ([type isEqualToString:@"1"]) {
        if (result.name.length != 0) {
            _addressSelect.origin = [NSString stringWithFormat:@"%@ %@", result.name, result.address];
            _currentAddress = [NSString stringWithFormat:@"%@ %@", result.name, result.address];
        } else {
            _addressSelect.origin = result.address;
            _currentAddress = result.address;
        }
        _originInfo = result;
    } else {
        if (result.name.length != 0) {
            _addressSelect.destination = [NSString stringWithFormat:@"%@ %@", result.name, result.address];
            _destinationAddress = [NSString stringWithFormat:@"%@ %@", result.name, result.address];
        } else {
            _addressSelect.destination = result.address;
            _destinationAddress = result.address;
        }
        _destinationInfo = result;
        self.addressSelect.isDestination = YES;
    }
}

- (void)searchNearPointWithResult:(BMKPoiInfo *)result {
    
}

#pragma mark - views Delegate

#pragma mark 选择终点
- (void)addressSelectClickDestination:(AddressSelectView *)view {
    SearchNearPointViewController * controller = [[SearchNearPointViewController alloc] init];
    controller.cityName = _cityName;
    controller.delegate = self;
    controller.type = @"2";
    [_mapView viewWillDisappear];
    [self.navigationController pushViewController:controller animated:YES];
}

#pragma mark 选择起点
- (void)addressSelectClickOrigin:(AddressSelectView *)view {
    SearchNearPointViewController * controller = [[SearchNearPointViewController alloc] init];
    controller.cityName = _cityName;
    controller.delegate = self;
    controller.type = @"1";
    [_mapView viewWillDisappear];
    [self.navigationController pushViewController:controller animated:YES];
}


#pragma mark 呼叫车辆
- (void)addressSelectNowCallCar:(AddressSelectView *)view {
    RideHailingViewController * controller = [[RideHailingViewController alloc] init];
    [_mapView viewWillDisappear];
    controller.model = self.model.rideHailing;
    controller.delegate = self;
    [self presentViewController:controller animated:YES completion:nil];
    _timer = [NSTimer timerWithTimeInterval:23 repeats:YES block:^(NSTimer * _Nonnull timer) {
        if (5 == _repeatCount) {
            
            _repeatCount = 0;
            [_timer invalidate];
            _timer = nil;
            self.addressSelect.destination = _destinationAddress;
            //    self.addressSelect.isDestination = NO;
            [self.model homeCancelCallCarWithComplete:^(id error) {
                [controller dismissViewControllerAnimated:YES completion:nil];
            }];
//            _repeatCount = 0;
//            [_timer invalidate];
//            self.addressSelect.isDestination = NO;
//            [self.model homeCancelCallCarWithComplete:^(id error) {
//                [controller dismissViewControllerAnimated:YES completion:nil];
//                [HUDManager showWarningWithText:@"暂时没有司机接单，请重新呼叫"];
//            }];
            return ;
        }
        _repeatCount++;
        NSLog(@"_repeatCount = %ld", (long)_repeatCount);
        [self.model homeCallCarWithOrigin:_currentAddress destination:_destinationAddress complete:^(id error) {
            if(!error) {
            }
        }];
    }];
    [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
    [_timer fire];
}

#pragma mark 呼叫成功
- (void)successfulAction {
    _repeatCount = 0;
    [_timer invalidate];
    _timer = nil;
//    self.addressSelect.isDestination = NO;
}

#pragma mark - 取消呼叫
- (void)rideHailingCancelOrder:(RideHailingViewController *)controller {
    _repeatCount = 0;
    [_timer invalidate];
    _timer = nil;
    self.addressSelect.destination = _destinationAddress;
//    self.addressSelect.isDestination = NO;
    [self.model homeCancelCallCarWithComplete:^(id error) {
      [controller dismissViewControllerAnimated:YES completion:nil];
    }];
}
#pragma mark - Private Method
- (void)myCenter {
    [self.mm_drawerController toggleDrawerSide:MMDrawerSideLeft animated:YES completion:nil];
}


- (GeoCodeSearchManager *)searchAddress {
    if(!_searchAddress) {
        _searchAddress = [[GeoCodeSearchManager alloc] init];
    }
    return _searchAddress;
}

- (AddressSelectView *)addressSelect {
    if(!_addressSelect) {
        AddressSelectView * view = [[AddressSelectView alloc] init];
        view.delegate = self;
        [self.view insertSubview:view aboveSubview:_mapView];
        __weak typeof(self) weakSelf = self;
        [view mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.equalTo(weakSelf.view);
        }];
        _addressSelect = view;
    }
    return _addressSelect;
}

- (HomeViewModel *)model {
    if(!_model) {
        _model = [[HomeViewModel alloc] init];
    }
    return _model;
}

@end
